<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加分类按钮-->
      <el-button type="primary" @click="showAddCate">添加分类</el-button>

      <!-- 树状图 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        show-index
        :selection-type="false"
        :expand-type="false"
        border
      >
        <!-- 是否有效 -->
        <template slot="isVaild" scope="scope">
          <i
            class="el-icon-success"
            style="color: lightgreen"
            v-if="!scope.row.cat_deleted"
          ></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="cat_deleted" scope="scope">
          <el-tag type="primary" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="active" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="showEditCate(scope.row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-setting"
            @click="deleteCate(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="addDialogClosed"
    >
      <!-- 表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="cat_name">
          <template>
            <!-- 级联选择器 -->
            <el-cascader
              v-model="pidList"
              :options="parentList"
              :props="props"
            ></el-cascader>
          </template>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateData">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改分类对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editDialogVisible"
      width="50%"
      @closed="editDialogClosed"
    >
      <!-- 表单 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Categories",
  data() {
    return {
      //   商品分类列表
      cateList: [],
      queryInfo: {
        type: "",
        pagenum: 1,
        pagesize: 5,
      },
      total: 0,
      // 表格各列的配置
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isVaild",
        },
        {
          label: "排序",
          type: "template",
          template: "cat_deleted",
        },
        {
          label: "操作",
          type: "template",
          template: "active",
        },
      ],
      //   添加分类
      addDialogVisible: false,
      addForm: {
        cat_pid: "",
        cat_name: "",
        cat_level: 0,
      },
      addFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
        cat_level: [
          { required: true, message: "请选择父级分类", trigger: "blur" },
        ],
      },
      props: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
      },
      //   选中的父id的数组
      pidList: [],
      // 级联选择器的数据
      parentList: [],
      // 编辑分类
      editDialogVisible: false,
      editForm: {
        cat_id: "",
        cat_name: "",
      },
      editFormRules: {
        cat_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //   获取商品列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) this.$message.error("获取商品列表失败");

      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },
    // 开启添加分类对话框
    async showAddCate() {
      this.addDialogVisible = true;
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      this.parentList = res.data;
    },
    // 关闭添加分类对话框
    addDialogClosed() {
      this.pidList = [];
      this.$refs.addFormRef.resetFields();
    },
    addCateData() {
      if (this.pidList.length === 0) {
        this.addForm.cat_pid = 0;
      } else {
        this.addForm.cat_pid = this.pidList[this.pidList.length - 1];
      }
      this.addForm.cat_level = this.pidList.length;

      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写参数名称");
        const { data: res } = await this.$http.post(`categories`, this.addForm);

        if (res.meta.status !== 201) return this.$message.error("创建失败");

        this.$message.success("创建成功");
        this.addDialogVisible = false;
        this.getCateList();
      });
    },
    // 开始编辑对话框
    showEditCate(row) {
      this.editForm.cat_id = row.cat_id;
      this.editForm.cat_name = row.cat_name;

      this.editDialogVisible = true;
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    editCateData() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写参数名称");

        const { data: res } = await this.$http.put(
          `categories/${this.editForm.cat_id}`,
          {
            cat_name: this.editForm.cat_name,
          }
        );
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("编辑失败");
        this.$message.success("编辑成功");
        this.editDialogVisible = false;
        this.getCateList();
      });
    },
    // 删除分类
    async deleteCate(row) {
      const confirmStr = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmStr !== "confirm") return this.$message.info("取消删除操作");

      const { data: res } = await this.$http.delete(`categories/${row.cat_id}`);
      if (res.meta.status !== 200) return this.$message.error("删除失败");

      this.$message.success("删除成功");
      this.getCateList();
    },
  },
};
</script>

<style scoped>
</style>